<?php
namespace app\admin\command;

use app\common\model\RebateModel;
use app\common\model\RewardModel;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use web\util\WebUtil;
use think\Log;
use app\common\service\MsgService;
use app\common\model\MemberModel;

class Settlement extends Command {

    protected function configure() {
        $this->setName('task')->setDescription('每个月月初,奖励结算');
    }

    protected function execute(Input $input, Output $output) {
        $month = date('Ym', strtotime(date('Y-m-01') . '-1 month'));

        $this->order_settle($input, $output, $month);

        $this->team_settle($input, $output, $month);

        $this->leader_settle($input, $output, $month);
    }

    /**
     * 订单奖励
     */
    private function order_settle(Input $input, Output $output, $month) {
        $output->writeln("订单奖励结算开始");
        $where = [
            'status' => 0,
            'type' => 1,
            'month' => $month
        ];

        $items = RewardModel::instance()->field('id,mid,money')
            ->where($where)
            ->select();

        $midMoneyMap = []; // 每个用户最后结算金额
        foreach ($items as $item) {
            $id = $item['id'];
            $mid = $item['mid'];
            $money = $item['money'];

            if (isset($midMoneyMap[$mid])) {
                $midMoneyMap[$mid] += $money;
            } else {
                $midMoneyMap[$mid] = $money;
            }

            Log::write("id:$id,mid:$mid update status 1");
            RewardModel::instance()->update([
                'id' => $id,
                'status' => 1,
                'settlement_time' => time()
            ]);
        }
        foreach ($midMoneyMap as $mid => $money) {
            Log::write("mid:$mid,incr money:$money");
            MemberModel::instance()->where('id', $mid)->setInc('rewardaccount', $money);
            $member = MemberModel::instance()->find($mid);
            if ($member['openid'] && $money > 0) {
                MsgService::sendOrderRewardMsgV2($member['openid'], $this->getMonth($month), $money);
            }
        }

        $output->writeln("订单奖励结算完成");
    }

    /**
     * 团队奖励
     */
    private function team_settle(Input $input, Output $output, $month) {
        $output->writeln("团队奖励结算开始");
        $where = [
            'status' => 0,
            'type' => 2,
            'month' => $month
        ];
        $rebateValue = RebateModel::instance()->where('type', 'TEAM')->value('value');
        $values = []; // 价格map
        if ($rebateValue) {
            $values = json_decode($rebateValue, true);
            krsort($values);
        }

        $items = RewardModel::instance()->where($where)->select();

        foreach ($items as $item) {
            $id = $item['id'];
            $mid = $item['mid'];
            // 总的未结算奖励
            $totalUnSettleWhere = [
                'mid' => $mid,
                'type' => 2,
                'status' => 0,
                'month' => $month
            ];
            $totalUnSettleCount = RewardModel::instance()->where($totalUnSettleWhere)->sum('num');
            // 总的子级未结算奖励
            // 一级子集
            $subMids = \app\common\model\MemberModel::instance()->getFristMebmerIdsByPid($mid);
            $subListMap = [];
            if ($subMids) {
                $subTotalUnSettleWhere = [
                    'mid' => [
                        'in',
                        $subMids
                    ],
                    'type' => 2,
                    'status' => 0,
                    'month' => $month
                ];
                $subListMap = RewardModel::instance()->where($subTotalUnSettleWhere)->column('id,num'); // 查询子级每个人金额
            }

            $price = 0;
            $price = WebUtil::getRewardPrice($values, $totalUnSettleCount);
            $subUnsettlePrice = 0;
            // 每个子级结算金额
            foreach ($subListMap as $sid => $val) {
                $subUnsettlePrice += $val * WebUtil::getRewardPrice($values, $val);
            }
            $unsettlePrice = $totalUnSettleCount * $price - $subUnsettlePrice; // //父级没有结算金额 - 子集没有结算金额

            Log::write("id:$id,mid:$mid,unsettlePrice:$unsettlePrice");
            RewardModel::instance()->update([
                'id' => $id,
                'money' => $unsettlePrice,
                'status' => 1,
                'settlement_time' => time()
            ]);
            MemberModel::instance()->where('id', $mid)->setInc('rewardaccount', $unsettlePrice);

            $member = MemberModel::instance()->find($mid);
            if ($member['openid'] && $unsettlePrice > 0) {
                MsgService::sendTeamRewardMsg($member['openid'], $this->getMonth($month), $unsettlePrice);
            }
        }
        $output->writeln("团队奖励结算完成");
    }

    /**
     * 领导奖励
     */
    private function leader_settle(Input $input, Output $output, $month) {
        $output->writeln("领导奖励结算开始");
        $type = 3;
        $where = [
            'status' => 0,
            'type' => $type,
            'month' => $month
        ];
        $rebate = RebateModel::instance()->where('type', 'LEADER')->find();
        $price = 0;
        $rebate && $price = floatval($rebate['value']);

        $items = RewardModel::instance()->where($where)->select();
        foreach ($items as $item) {
            $id = $item['id'];
            $mid = $item['mid'];
            // 总的未结算奖励
            $totalUnSettleWhere = [
                'mid' => $mid,
                'type' => $type,
                'status' => 0,
                'month' => $month
            ];
            $totalUnSettleCount = RewardModel::instance()->where($totalUnSettleWhere)->sum('num');

            // 总的子级未结算奖励
            // 一级子集
            $subMids = \app\common\model\MemberModel::instance()->where('fid', $mid)
                ->where('grade', 2)
                ->column('id');
            $subUnSettleCount = 0;
            if ($subMids) {
                $subTotalUnSettleWhere = [
                    'mid' => [
                        'in',
                        $subMids
                    ],
                    'type' => $type,
                    'status' => 0,
                    'month' => $month
                ];
                $subUnSettleCount = RewardModel::instance()->where($subTotalUnSettleWhere)->sum('num'); // 查询子级每个人金额
            }
            // 每个子级结算金额
            $unsettlePrice = ($totalUnSettleCount - $subUnSettleCount) * $price; // //父级没有结算金额 - 子集没有结算金额

            Log::write("id:$id,mid:$mid,unsettlePrice:$unsettlePrice");
            RewardModel::instance()->update([
                'id' => $id,
                'money' => $unsettlePrice,
                'status' => 1,
                'settlement_time' => time()
            ]);
            MemberModel::instance()->where('id', $mid)->setInc('rewardaccount', $unsettlePrice);

            $member = MemberModel::instance()->find($mid);
            if ($member['openid'] && $unsettlePrice > 0) {
                MsgService::sendLeaderRewardMsg($member['openid'], $this->getMonth($month), $unsettlePrice);
            }
        }
        $output->writeln("领导奖励结算结束");
    }

    private function getMonth($month) {
        return date('m', strtotime($month . '01'));
    }
}